package com.yanqu.road.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class JsonUtils {

    private static Logger logger = LogManager.getLogger(JsonUtils.class);

    public static String toJSONString(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.error("to json error." ,e);
            throw new RuntimeException(e);
        }
    }


    public static <T> T parseObject(String text, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(text, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> YQTypeReference) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(text, YQTypeReference);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param text
     * @param clazz
     * @param FAIL_ON_UNKNOWN_PROPERTIES 反序列化时,遇到未知属性(那些没有对应的属性来映射的属性,并且没有任何setter或handler来处理这样的属性)时是否引起结果失败
     *                                   还可以使用 @JsonIgnoreProperties(ignoreUnknown = true)注解
     * @param <T>
     * @return
     */
    public static <T> T parseObject(String text, Class<T> clazz, boolean FAIL_ON_UNKNOWN_PROPERTIES) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_UNKNOWN_PROPERTIES);
            return mapper.readValue(text, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
